﻿using DeHeng_Mes.Utils;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

/// <summary>
/// 写入日志帮助类
/// </summary>
public class AsyncLoggerDevice : IDisposable{

    static String basePath = EncryptOrDecrypt.Instance.Decrypt(SettingsManager.Instance.GetSetting("SaveLogPath"));
    private string LogRootDirectory = string.IsNullOrEmpty(basePath) ? Environment.CurrentDirectory : basePath + "\\Logs";
    private const int MaxFileSize = 1024 * 1024; // 1MB  
    private const string LogFileExtension = ".txt";
    private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
    private string _currentDirectory;
    private FileInfo _currentFileInfo;
    private StreamWriter _currentStreamWriter;

    public AsyncLoggerDevice() {
        InitializeCurrentDirectoryAndFile();
    }

    private void InitializeCurrentDirectoryAndFile() {
            // 创建或获取当前日期的目录  
            _currentDirectory = Path.Combine(LogRootDirectory, DateTime.Now.ToString("yyyy-MM-dd"));
            if (!Directory.Exists(_currentDirectory)) {
                Directory.CreateDirectory(_currentDirectory);
            }

            // 在当前目录中找到最新的txt文件  
            var files = Directory.GetFiles(_currentDirectory, "*" + LogFileExtension)
                .OrderByDescending(f => new FileInfo(f).LastWriteTime)
                .ToList();

            if (files.Any()) {
                // 获取最新的txt文件  
                var latestFile = files.First();
                _currentFileInfo = new FileInfo(latestFile);

                // 检查文件大小，如果超过限制则创建新文件  
                if (_currentFileInfo.Length >= MaxFileSize) {
                    CreateNewLogFile();
                } else {
                    // 初始化StreamWriter以追加到现有文件  
                    _currentStreamWriter = new StreamWriter(File.Open(_currentFileInfo.FullName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite), Encoding.UTF8);
                }
            } else {
                // 如果没有找到文件，则创建新的txt文件  
                CreateNewLogFile();
            }
    }

    private void CreateNewLogFile() {
        // 创建新的日志文件  
        string logFileName = Path.Combine(_currentDirectory, DateTime.Now.ToString("HH点mm分ss秒") + "_log_Device" + LogFileExtension);
        _currentFileInfo = new FileInfo(logFileName);
        _currentStreamWriter = new StreamWriter(File.Open(_currentFileInfo.FullName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite), Encoding.UTF8);
    }

    private async Task WriteToFileAsync(string message) {
        await _semaphore.WaitAsync();
        try {
            message = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + message;
            // 写入日志消息  
            await _currentStreamWriter.WriteLineAsync(message);
            await _currentStreamWriter.FlushAsync();
        } catch (Exception) {
            
        } finally {
            _semaphore.Release();
        }
    }

    public void Dispose() {
        _currentStreamWriter?.Dispose();
        _currentStreamWriter = null;
    }

    public static async Task WriteLogAsync(string message) {
        using (AsyncLoggerDevice logger = new AsyncLoggerDevice()) {
            await logger.WriteToFileAsync(message);
        }
    }
}